<?php
/*
 * This file is part of EC-CUBE
 *
 * Copyright(c) 2000-2012 LOCKON CO.,LTD. All Rights Reserved.
 *
 * http://www.lockon.co.jp/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

// {{{ requires
require_once CLASS_EX_REALDIR . 'page_extends/LC_Page_Ex.php';

/**
 * 会員登録のページクラス.
 *
 * @package Page
 * @author LOCKON CO.,LTD.
 * @version $Id: LC_Page_Regist.php 21950 2012-07-02 11:42:51Z pineray $
 */
class LC_Page_Elect extends LC_Page_Ex {

    // {{{ properties

    // }}}
    // {{{ functions
    /**
     * Page を初期化する.
     *
     * @return void
     */
    function init() {
    	
        parent::init();
      	
       	//引入本页面javascript
	   	$this->linkCss[] = 'css/sapaImport.css';
        $this->link_javascript[] = "js/sapa/jquery.dataTables.js";
        
	   	
    }

    /**
     * Page のプロセス.
     *
     * @return void
     */
    function process() {
        //parent::process();
        $this->action();
        $this->sendResponse();
    }

    /**
     * Page のAction.
     *
     * @return void
     */
    function action() {
        switch ($this->getMode()) {
        	//Entre Creat new elect 
        	case 'newEcect':
        		$this->linkCss[] = 'css/datepickerImport.css';
		        $this->link_javascript[] = "js/sapa/jquery.ui.core.js";
		        $this->link_javascript[] = "js/sapa/jquery.ui.datepicker.js";
		        $this->link_javascript[] = "js/sapa/jquery.ui.widget.js";
        		$this->adminAuthorityCheck(AUTHORITY_ELECT_ADMIN);
        		$this->tpl_mainpage = 'elect/elect.tpl';
                break;
            // Elect confirm
        	case 'confirm':
        		$this->adminAuthorityCheck(AUTHORITY_ELECT_ADMIN);
        		$this->tpl_mainpage = 'elect/elect_detail.tpl';
        		$this->getElectDataFrompost();
                break;
            // elect info insert to DB
            case 'creatElect':
            	$this->adminAuthorityCheck(AUTHORITY_ELECT_ADMIN);
            	$this->getElectDataFrompost();
            	//DB insert
            	$this->insertElectInfoToDB();
            	
            	$this->tpl_mainpage = 'elect/elect_list.tpl';
            	break;
            //Elect Block
        	case 'electBlock':
        		$this->adminAuthorityCheck(AUTHORITY_ELECT_ADMIN);
        		$this->updateMstElectTable('1');
        		SC_Response_Ex::sendRedirect(HTTP_URL."elect/elect.php");
                break;
            //Elect Active
        	case 'electActive':
        		$this->adminAuthorityCheck(AUTHORITY_ELECT_ADMIN);
        		$this->updateMstElectTable('0');
        		SC_Response_Ex::sendRedirect(HTTP_URL."elect/elect.php");
                break;
            // Elect confirm
        	case 'seeElectDetail':
        		$this->tpl_mainpage = 'elect/elect_result.tpl';
        		$this->getElectDataFromDb();
                break;
                
            // seeVoter
        	case 'seeVoter':
        		$this->adminAuthorityCheck(AUTHORITY_ELECT_ADMIN);
        		$this->tpl_mainpage = 'elect/elect_seeVoter.tpl';
        		$this->getVoterInnfo();
                break;
            //--　それ以外のアクセスは無効とする
            default:
            	//只有管理员权限才能登陆这个画面
		        $this->adminAuthorityCheck(AUTHORITY_ELECT_ADMIN);
		        
		       	$this->tpl_mainpage = 'elect/elect_list.tpl';
		       	$this->electInfoArr = $this->getElectInfo();
                break;
        }
    }

    /**
     * デストラクタ.
     *
     * @return void
     */
    function destroy() {
        parent::destroy();
    }
    
    function getElectDataFrompost(){
    			$this->electionTilte = $this->getValFromPostOrGet("election");
        		$this->startDate = $this->getValFromPostOrGet("startDate");
        		$this->endDate = $this->getValFromPostOrGet("endDate");
        		
        		$this->positionNameArr = $this->getValFromPostOrGet("positionName");
        		$this->selectMaxArr = $this->getValFromPostOrGet("selectMax");
        		$this->candidateArr = $this->getValFromPostOrGet("candidate");
    }
    
    function insertElectInfoToDB(){
    	
    	$objQuery = SC_Query::getSingletonInstance();
        $objQuery->begin();
        
        //1 选举表 mst_elect
    	$arrInsMstElect = $this->getInsertMstElect();
    	$objQuery->insert('mst_elect', $this->getInsertMstElect());
    	
    	//2 选举职位表tab_elect_position
    	$arrInsertPosition = $this->getInsertTabElectPosition();
    	foreach ($arrInsertPosition as $index => $position) {
    		$objQuery->insert('tab_elect_position',$position);
    		//3 候选人表tab_elect_candidate
    		$arrInsCandidate = $this->getInsertTabElectCandidate($index);
    		foreach ($arrInsCandidate as $insCandidate) {
    			$objQuery->insert('tab_elect_candidate',$insCandidate);
    		}
    	}
    	//插入数据库时 出错了	
		if ($objQuery->isError()) {
			$objQuery->rollback();
			SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
			break;
		}else{
			$objQuery->commit();
		}
    }
    
    function getInsertMstElect(){
    	$retrunArr = array();
    	
    	//$retrunArr['id'] = '  ';														//举ID		
		$retrunArr['elect_title'] = $this->electionTilte;          						//选举名	
		$retrunArr['publisher_id'] = $this->objSess->GetSession('user_id');          	//发布者ID	
		$retrunArr['publisher_lastname'] = $this->objSess->GetSession('lastname');   	//发布者（姓）
		$retrunArr['publisher_firstname'] = $this->objSess->GetSession('firstname'); 	//发布者（名）
		$retrunArr['start_time'] = $this->startDate;            						//投票开始日
		$retrunArr['close_time'] = $this->endDate;            							//投票结束日
		$retrunArr['status'] = '0';               		 								//状态	 0： 正常  该项目暂时没用  	
		$retrunArr['del_flg'] = '0';               										//削除フラグ
		$retrunArr['create_time'] = 'now()';        									//作成日時	
		$retrunArr['update_time'] = 'now()';        									//更新日時	
    	
    	return $retrunArr;
    }
    
	function getInsertTabElectPosition(){
		
    	$retrunArr = array();
    	$objQuery = SC_Query::getSingletonInstance();
		$maxId = $objQuery->select('LAST_INSERT_ID() AS id','mst_elect');
		
	 	foreach ($this->positionNameArr as $i =>$position) {        
	    	//$retrunArr['id'] = '';									//职位ID
			$retrunArr[$i]['elect_id'] = $maxId[0]['id'];        		//选举ID
			$retrunArr[$i]['position_name'] = $position;   				//职位名
			$retrunArr[$i]['number_limite'] = $this->selectMaxArr[$i];  //可选举人数上限
			$retrunArr[$i]['del_flg'] = '0';         					//削除フラグ
			$retrunArr[$i]['create_time'] = 'now()';     				//作成日時
			$retrunArr[$i]['update_time'] = 'now()';     				//更新日時
	 	}
    	return $retrunArr;
    }
    
	function getInsertTabElectCandidate($index){
    	$retrunArr = array();
    	
    	$objQuery = SC_Query::getSingletonInstance();
		$maxId = $objQuery->select('LAST_INSERT_ID() AS id','tab_elect_position');
			foreach ($this->candidateArr[$index] as $i =>$candidate) { 
				//$retrunArr['id'] = ;
				$retrunArr[$i]['elect_position_id'] = $maxId[0]['id'];
				$retrunArr[$i]['candidature_name'] = $candidate;
				$retrunArr[$i]['del_flg'] = '0';
				$retrunArr[$i]['create_time'] = 'now()';
				$retrunArr[$i]['update_time'] = 'now()';
			}
    	return $retrunArr;
    }
   
    function getElectInfo(){
    	$rs = array();
    	
    	$objQuery = SC_Query::getSingletonInstance();
    	$rs= $objQuery->select("*","mst_elect");
    	return $rs;
    }
    /**
     * 
     *更新数据库的del_flg字段值
     * @param unknown_type $valOfDelFlg  0 正常  1 删除
     */
    function updateMstElectTable ($valOfDelFlg){
    	
    	$id= $this->getValFromPostOrGet('id');
    	$arrVal = array();
    	$arrVal['del_flg'] = $valOfDelFlg;
    	$where = ' id = ?';
    	$arrWhereVal = array($id);
    	
    	$objQuery = SC_Query::getSingletonInstance();
    	$objQuery->update('mst_elect', $arrVal, $where,$arrWhereVal);
    }
    /**
     * 从选举一览画面查看选举结果
     * Enter description here ...
     */
    function getElectDataFromDb(){
    	//选举ID
    	$id= $this->getValFromPostOrGet('id');
    	
    	//查询数据库 取得该选举信息
    	$objQuery = SC_Query::getSingletonInstance();
    	
    	$electInfo = $objQuery->select('id,elect_title,start_time,close_time','mst_elect','id=?' ,array($id));
    	$this->electionTilte = $electInfo[0]['elect_title'];
        $this->startDate = $electInfo[0]['start_time'];
        $this->endDate = $electInfo[0]['close_time'];
        //投票总人数  得票数  状态
        
		//职位信息
        $this->positionInfoArr = $objQuery->select('id,position_name,number_limite','tab_elect_position','elect_id=?' ,array($id));
        
        $this->candidateArr = array();
        //候选人信息
        foreach ($this->positionInfoArr as $i =>$positionInfo) {
        	
        	$candidateInfoArr = $objQuery->select('id,candidature_name','tab_elect_candidate','elect_position_id=?' ,array($positionInfo['id']));
        	
        	$tempArr = array();
        	foreach ($candidateInfoArr as $candidateInfo) {
        		//得票数
        		$voteWhereArr = array($id,$positionInfo['id'],$candidateInfo['id']);
        		$candidateInfo['count'] = $objQuery->count('tab_vote', 'elect_id = ? and positio_id = ? and candidate_id =?',$voteWhereArr);
        		
        		array_push($tempArr,$candidateInfo);
        	}
        	$this->candidateArr[] = $tempArr;
        }  
              
    }
    
    //查看投票人candidatureName
    function getVoterInnfo(){
    	$this->name = $this->getValFromPostOrGet('candidateName');
    	$this->count = $this->getValFromPostOrGet('obtain');
    	$id = $this->getValFromPostOrGet('id');
    	
    	$objQuery = SC_Query::getSingletonInstance();
    	$this->obtainInfo = $objQuery->select('voter_lastname,voter_firstname,candidature_lastname','tab_vote','candidate_id =?',array($id));
    }
    
}